package org.lab.mtga.core.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.lab.mtga.core.guice.MTGACoreModule;
import org.lab.mtga.core.jpa.EntityManagerProvider;
import org.lab.mtga.core.model.Card;
import org.lab.mtga.core.model.CardType;

import com.google.inject.Guice;
import com.google.inject.Injector;

public class MagicCardCrawlerRunner {

	public static void main(String[] args) throws InterruptedException {
		Injector injector = Guice.createInjector(new MTGACoreModule());
		injector.getInstance(MagicCardCrawler.class).run();
	}

	@Inject
	private EntityManagerProvider entityManagerProvider;

	public void run() {
		Long delay = 2000L;
		EntityManager entityManager = entityManagerProvider.get();
		TypedQuery<Card> query = entityManager.createQuery("select c from Card c where c.id > :id", Card.class);
		query.setParameter("id", 82);
		List<Card> cards = query.getResultList();
		for (Card card : cards) {
			MagicCardCrawler crawler = new MagicCardCrawler(card, entityManagerProvider);
			crawler.run();
			try {
				Thread.sleep(delay);
			} catch (Exception ignore) {
			}
		}
		fixInitialImport();
	}

	private void fixInitialImport() {
		EntityManager entityManager = entityManagerProvider.get();
		TypedQuery<Card> query = entityManager.createQuery("select e from Card e where e.name in :names", Card.class);
		query.setParameter("names", Arrays.asList("Island", "Plains", "Forest", "Mountain", "Swamp"));
		entityManager.getTransaction().begin();
		for (Card card : query.getResultList()) {
			card.setTypes(new ArrayList<CardType>());
			card.getTypes().add(CardType.Land);
			card.getTypes().add(CardType.BasicLand);
			entityManager.merge(card);
		}
		updateType("Tarmogoyf", entityManager, CardType.Creature);
		updateType("Silence", entityManager, CardType.Instant);
		updateType("Slaughter Pact", entityManager, CardType.Instant);
		updateType("Wear // Tear", entityManager, CardType.Instant);
		entityManager.getTransaction().commit();
	}

	private void updateType(String name, EntityManager entityManager, CardType... type) {
		TypedQuery<Card> query = entityManager.createQuery("select e from Card e where e.name = :name", Card.class);
		query.setParameter("name", name);
		Card card = query.getSingleResult();
		card.setTypes(Arrays.asList(type));
		entityManager.merge(card);
	}
}
